<?php

namespace app\model\frontend;

use think\Model;
use think\facade\Db;

/**
 * 盲盒前台模型类
 * Class BlindBoxModel
 * @package app\model\frontend
 */
class BlindBoxModel extends Model
{
    protected $pk = 'id';
    protected $table = 'sh_blind_box';

    /**
     * 获取盲盒列表（前台展示）
     * @param int $uniacid 站点ID
     * @param array $filter 筛选条件
     * @return array
     */
    public static function get_list($uniacid, $filter = [])
    {
        $where = ' bb.uniacid = ' . intval($uniacid);
        
        // 默认只查询未删除且上架的盲盒
        $where .= " AND bb.is_deleted = 0";
        $where .= " AND bb.status = 1";
        
        if (!empty($filter['name'])) {
            $where .= " AND bb.name LIKE '%" . addslashes($filter['name']) . "%'";
        }
        
        $sql = 'SELECT bb.*, 
                COUNT(bbp.id) as prize_count,
                SUM(CASE WHEN bbp.status = 1 THEN 1 ELSE 0 END) as active_prize_count
                FROM sh_blind_box bb
                LEFT JOIN sh_blind_box_prize bbp ON bb.id = bbp.blind_box_id
                WHERE ' . $where . '
                GROUP BY bb.id
                ORDER BY bb.sort_order ASC, bb.id DESC';
        
        return Db::query($sql);
    }

    /**
     * 获取盲盒详情
     * @param int $uniacid 站点ID
     * @param int $blind_box_id 盲盒ID
     * @return array|null
     */
    public static function detail($uniacid, $blind_box_id)
    {
        $sql = "SELECT bb.* 
                FROM sh_blind_box bb
                WHERE bb.id = " . intval($blind_box_id) . " 
                AND bb.uniacid = " . intval($uniacid) . "
                AND bb.is_deleted = 0";
        
        $result = Db::query($sql);
        return !empty($result) ? $result[0] : null;
    }

    /**
     * 获取盲盒奖品列表
     * @param int $uniacid 站点ID
     * @param int $blind_box_id 盲盒ID
     * @return array
     */
    public static function get_prizes($uniacid, $blind_box_id)
    {
        $sql = "SELECT bbp.*, g.image as goods_image, g.price as goods_price
                FROM sh_blind_box_prize bbp
                LEFT JOIN sh_goods g ON bbp.prize_type = 'goods' AND bbp.prize_id = g.id AND g.uniacid = " . intval($uniacid) . "
                WHERE bbp.blind_box_id = " . intval($blind_box_id) . "
                ORDER BY bbp.sort_order ASC, bbp.id ASC";
        
        return Db::query($sql);
    }

    /**
     * 抽取盲盒（核心抽奖逻辑）
     * @param int $uniacid 站点ID
     * @param int $blind_box_id 盲盒ID
     * @param int $customer_id 用户ID
     * @param int $order_id 订单ID
     * @return array|false 中奖信息或false
     */
    public static function draw($uniacid, $blind_box_id, $customer_id, $order_id = null)
    {
        
        // 获取可用奖品列表（状态启用且有库存）
        $sql = "SELECT * FROM sh_blind_box_prize 
                WHERE blind_box_id = " . intval($blind_box_id) . " 
                AND status = 1 
                AND (remain_stock > 0 OR remain_stock = -1)
                ORDER BY sort_order ASC";
        
        $prizes = Db::query($sql);
        
        if (empty($prizes)) {
            return false;
        }
        
        // 计算总概率
        $total_probability = 0;
        foreach ($prizes as $prize) {
            $total_probability += floatval($prize['probability']);
        }
        
        // 生成随机数
        $random = mt_rand(1, intval($total_probability * 100)) / 100;
        
        // 确定中奖奖品
        $current_probability = 0;
        $winning_prize = null;
        
        foreach ($prizes as $prize) {
            $current_probability += floatval($prize['probability']);
            if ($random <= $current_probability) {
                $winning_prize = $prize;
                break;
            }
        }
        
        if (!$winning_prize) {
            $winning_prize = end($prizes); // 兜底，返回最后一个奖品
        }
        
        // 扣减库存
        if ($winning_prize['remain_stock'] > 0) {
            $update_stock_sql = "UPDATE sh_blind_box_prize 
                                 SET remain_stock = remain_stock - 1 
                                 WHERE id = " . intval($winning_prize['id']);
            Db::execute($update_stock_sql);
        }
        
        // 增加盲盒已售数量
        $update_sold_sql = "UPDATE sh_blind_box 
                           SET sold = sold + 1 
                           WHERE id = " . intval($blind_box_id);
        Db::execute($update_sold_sql);
        
        // 获取盲盒名称
        $blind_box = self::detail($uniacid, $blind_box_id);
        
        // 记录抽奖记录
        $time = date('Y-m-d H:i:s');
        $record_sql = "INSERT INTO sh_blind_box_record SET
                      uniacid = " . $uniacid . ",
                      blind_box_id = " . intval($blind_box_id) . ",
                      blind_box_name = '" . addslashes($blind_box['name']) . "',
                      customer_id = " . intval($customer_id) . ",
                      order_id = " . ($order_id ? intval($order_id) : "NULL") . ",
                      prize_id = " . intval($winning_prize['id']) . ",
                      prize_type = '" . addslashes($winning_prize['prize_type']) . "',
                      prize_name = '" . addslashes($winning_prize['prize_name']) . "',
                      prize_image = '" . addslashes($winning_prize['prize_image']) . "',
                      prize_value = '" . addslashes($winning_prize['prize_value']) . "',
                      prize_level = '" . addslashes($winning_prize['prize_level']) . "',
                      create_time = '" . $time . "'";
        
        Db::execute($record_sql);
        $record_id = Db::name('sh_blind_box_record')->getLastInsID();
        
        return [
            'record_id' => $record_id,
            'prize' => $winning_prize
        ];
    }

    /**
     * 获取用户抽奖记录（关联订单信息）
     * @param int $uniacid 站点ID
     * @param int $customer_id 用户ID
     * @param array $filter 筛选条件
     * @return array
     */
    public static function get_user_records($uniacid, $customer_id, $filter = [])
    {
        $where = " bbr.uniacid = " . intval($uniacid);
        $where .= " AND bbr.customer_id = " . intval($customer_id);
        
        if (!empty($filter['blind_box_id'])) {
            $where .= " AND bbr.blind_box_id = " . intval($filter['blind_box_id']);
        }
        
        if (!empty($filter['order_id'])) {
            $where .= " AND bbr.order_id = " . intval($filter['order_id']);
        }
        
        // 关联订单表获取订单信息
        $sql = "SELECT bbr.*, 
                bb.image as blind_box_image,
                bb.price as blind_box_price,
                o.id as order_id,
                o.order_no,
                o.total as order_total,
                o.is_payed,
                o.status as order_status,
                o.payment_method,
                o.create_time as order_create_time,
                o.shipping_method,
                obb.quantity as order_quantity,
                obb.is_drawn,
                obb.draw_time
                FROM sh_blind_box_record bbr
                LEFT JOIN sh_blind_box bb ON bbr.blind_box_id = bb.id
                LEFT JOIN sh_order o ON bbr.order_id = o.id
                LEFT JOIN sh_order_blind_box obb ON bbr.order_id = obb.order_id AND bbr.blind_box_id = obb.blind_box_id
                WHERE " . $where . "
                ORDER BY bbr.create_time DESC";
        
        return Db::query($sql);
    }

    /**
     * 检查用户是否达到购买限制
     * @param int $uniacid 站点ID
     * @param int $blind_box_id 盲盒ID
     * @param int $customer_id 用户ID
     * @return array ['can_buy' => bool, 'bought_count' => int, 'limit' => int]
     */
    public static function check_user_limit($uniacid, $blind_box_id, $customer_id)
    {
        $blind_box = self::detail($uniacid, $blind_box_id);
        
        if (empty($blind_box) || $blind_box['limit_per_user'] == 0) {
            return ['can_buy' => true, 'bought_count' => 0, 'limit' => 0];
        }
        
        $sql = "SELECT COUNT(*) as count 
                FROM sh_blind_box_record 
                WHERE uniacid = " . intval($uniacid) . "
                AND blind_box_id = " . intval($blind_box_id) . " 
                AND customer_id = " . intval($customer_id);
        
        $result = Db::query($sql);
        $bought_count = intval($result[0]['count']);
        
        $can_buy = $bought_count < $blind_box['limit_per_user'];
        
        return [
            'can_buy' => $can_buy,
            'bought_count' => $bought_count,
            'limit' => $blind_box['limit_per_user']
        ];
    }

    /**
     * 关联盲盒订单（记录盲盒订单关系）
     * @param int $uniacid 站点ID
     * @param int $blind_box_id 盲盒ID
     * @param int $order_id 订单ID
     * @param int $quantity 购买数量
     * @return bool
     */
    public static function link_order($uniacid, $blind_box_id, $order_id, $quantity = 1)
    {
        $time = date('Y-m-d H:i:s');
        
        $sql = "INSERT INTO sh_order_blind_box SET
                uniacid = " . $uniacid . ",
                blind_box_id = " . intval($blind_box_id) . ",
                order_id = " . intval($order_id) . ",
                quantity = " . intval($quantity) . ",
                is_drawn = 0,
                create_time = '" . $time . "'";
        
        return Db::execute($sql);
    }

    /**
     * 获取盲盒订单记录
     * @param int $uniacid 站点ID
     * @param array $where 查询条件
     * @return array|null
     */
    public static function get_order_blind_box($uniacid, $where = [])
    {
        $sql_where = "uniacid = " . intval($uniacid);
        
        if (isset($where['id'])) {
            $sql_where .= " AND id = " . intval($where['id']);
        }
        if (isset($where['order_id'])) {
            $sql_where .= " AND order_id = " . intval($where['order_id']);
        }
        if (isset($where['blind_box_id'])) {
            $sql_where .= " AND blind_box_id = " . intval($where['blind_box_id']);
        }
        if (isset($where['is_drawn'])) {
            $sql_where .= " AND is_drawn = " . intval($where['is_drawn']);
        }
        
        $sql = "SELECT * FROM sh_order_blind_box WHERE " . $sql_where . " LIMIT 1";
        $result = Db::query($sql);
        
        return !empty($result) ? $result[0] : null;
    }

    /**
     * 标记盲盒订单为已抽奖
     * @param int $order_blind_box_id 盲盒订单ID
     * @return bool
     */
    public static function mark_order_drawn($order_blind_box_id)
    {
        $time = date('Y-m-d H:i:s');
        
        $sql = "UPDATE sh_order_blind_box SET
                is_drawn = 1,
                draw_time = '" . $time . "'
                WHERE id = " . intval($order_blind_box_id);
        
        return Db::execute($sql);
    }

    /**
     * 获取盲盒订单详情（前台用户）
     * @param int $uniacid 站点ID
     * @param int $order_id 订单ID
     * @param int $customer_id 用户ID
     * @return array|null
     */
    public static function get_order_detail($uniacid, $order_id, $customer_id)
    {
        // 查询订单基本信息，验证订单归属
        $sql = "SELECT 
                    o.*,
                    obb.blind_box_id,
                    obb.quantity as blind_box_quantity,
                    obb.is_drawn,
                    obb.draw_time,
                    bb.name as blind_box_name,
                    bb.image as blind_box_image,
                    bb.price as blind_box_price,
                    bb.description as blind_box_description
                FROM sh_order o
                LEFT JOIN sh_order_blind_box obb ON o.id = obb.order_id
                LEFT JOIN sh_blind_box bb ON obb.blind_box_id = bb.id
                WHERE o.id = " . intval($order_id) . "
                AND o.uniacid = " . intval($uniacid) . "
                AND o.customer_id = " . intval($customer_id);
        
        $result = Db::query($sql);
        
        if (empty($result)) {
            return null;
        }
        
        $order = $result[0];
        
        // 查询订单商品
        $goods_sql = "SELECT * FROM sh_order_goods WHERE order_id = " . intval($order_id);
        $order['goods'] = Db::query($goods_sql);
        
        // 查询订单总计
        $total_sql = "SELECT * FROM sh_order_total WHERE order_id = " . intval($order_id);
        $totals = Db::query($total_sql);
        $order['total_items'] = [];
        foreach ($totals as $total) {
            $order['total_items'][$total['code']] = [
                'name' => $total['code'],
                'value' => $total['value']
            ];
        }
        
        // 查询自提信息（如果有）
        if ($order['shipping_method'] == 'pickup') {
            $pickup_sql = "SELECT * FROM sh_order_pickup WHERE order_id = " . intval($order_id);
            $pickup_result = Db::query($pickup_sql);
            $order['pickup_info'] = !empty($pickup_result) ? $pickup_result[0] : null;
        }
        
        // 查询抽奖记录
        if ($order['is_drawn'] == 1) {
            $record_sql = "SELECT bbr.*
                          FROM sh_blind_box_record bbr
                          WHERE bbr.order_id = " . intval($order_id) . "
                          AND bbr.uniacid = " . intval($uniacid) . "
                          AND bbr.customer_id = " . intval($customer_id) . "
                          ORDER BY bbr.create_time ASC";
            $order['draw_records'] = Db::query($record_sql);
        } else {
            $order['draw_records'] = [];
        }
        
        return $order;
    }
}
